package com.yuanmei.datas;

import com.yuanmei.model.HistoryDayQuote;
import com.yuanmei.common.Utils;
import com.yuanmei.model.KLineChartQuote;
import com.yuanmei.model.StockItem;
import com.yuanmei.model.TdxStockInfo;
import com.yuanmei.model.TodayQuote;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmResults;
import io.realm.Sort;

public class DBUtils {
    public static final String TAG = "DBUtils";

    public static TodayQuote getTodayQuoteByCode(String neteaseCode) {
        TodayQuote res = null;
        RealmConfiguration todayRealmConfig = new RealmConfiguration.Builder()
                .name("today_quotes.realm")
                .deleteRealmIfMigrationNeeded()
                .build();
        Realm realm = Realm.getInstance(todayRealmConfig);
        RealmResults<TodayQuote> results = realm.where(TodayQuote.class).
                equalTo("necode", neteaseCode).findAll();
        if (results.size() == 1) {
            List<TodayQuote> resList = realm.copyFromRealm(results);
            res = resList.get(0);
        }
        realm.close();
        return res;
    }

    public static TodayQuote flushAndGetTodayQuoteByCode(String neCode) {
        TodayQuote res = null;
        RealmConfiguration todayRealmConfig = new RealmConfiguration.Builder()
                .name("today_quotes.realm")
                .deleteRealmIfMigrationNeeded()
                .build();
        Realm realm = Realm.getInstance(todayRealmConfig);
        ArrayList<String> stockCodeList = new ArrayList<>();
        stockCodeList.add(neCode);
        FetchDataService.fetchTodayQuotes(
                stockCodeList, realm);

        RealmResults<TodayQuote> results =
                realm.where(TodayQuote.class).
                        equalTo("necode", neCode).findAll();
        if (results.size() == 1) {
            List<TodayQuote> resList = realm.copyFromRealm(results);
            res = resList.get(0);
        }

        realm.close();
        return res;
    }

    public static TdxStockInfo getTdxStockInfoInstance(String code) {
        int iCode;
        TdxStockInfo result = null;
        try {
            iCode = Integer.valueOf(code);
        } catch (NumberFormatException e) {
            return null;
        }

        RealmConfiguration stockBasicConfig = new RealmConfiguration.Builder()
                .name(TdxStockInfoRealm.RealmName)
                .deleteRealmIfMigrationNeeded()
                .build();
        Realm realm = Realm.getInstance(stockBasicConfig);
        RealmResults<TdxStockInfo> results =
                realm.where(TdxStockInfo.class).
                        equalTo("code", iCode).findAll();
        if (results.size() > 0) {
            List<TdxStockInfo> objList = realm.copyFromRealm(results);
            result = objList.get(0);
        }
        realm.close();
        return result;
    }

    public static List<StockItem> getIndustryList(String industry) {
        List<StockItem> industryList = new ArrayList<>();
        RealmConfiguration stockBasicConfig = new RealmConfiguration.Builder()
                .name(TdxStockInfoRealm.RealmName)
                .deleteRealmIfMigrationNeeded()
                .build();
        Realm realm = Realm.getInstance(stockBasicConfig);
        RealmResults<TdxStockInfo> results =
                realm.where(TdxStockInfo.class).
                        equalTo("industry", industry).findAll();
        if (results.size() > 0) {
            List<TdxStockInfo> objList = realm.copyFromRealm(results);
            for (TdxStockInfo tsi : objList) {
                String code = String.format(Locale.CHINA,"%06d", tsi.getCode());
                StockItem si = new StockItem(tsi.getName(), code, tsi, false);
                industryList.add(si);
            }
        }
        realm.close();
        return industryList;
    }

    public static List<StockItem> getAreaList(String area) {
        List<StockItem> areaList = new ArrayList<>();
        RealmConfiguration stockBasicConfig = new RealmConfiguration.Builder()
                .name(TdxStockInfoRealm.RealmName)
                .deleteRealmIfMigrationNeeded()
                .build();
        Realm realm = Realm.getInstance(stockBasicConfig);
        RealmResults<TdxStockInfo> results =
                realm.where(TdxStockInfo.class).
                        equalTo("area", area).findAll();
        if (results.size() > 0) {
            List<TdxStockInfo> objList = realm.copyFromRealm(results);
            for (TdxStockInfo tsi : objList) {
                String code = String.format(Locale.CHINA,"%06d", tsi.getCode());
                StockItem si = new StockItem(tsi.getName(), code, tsi, false);
                areaList.add(si);
            }
        }
        realm.close();
        return areaList;
    }

    public static List<KLineChartQuote> getIndexDayQuotesByIDates(
            String neIndexCode,
            List<Integer> iDateList) {

        if (iDateList.size() <= 1)
            return null;

        int iDatesSize = iDateList.size();
        int startIDate = iDateList.get(0);
        int endIDate = iDateList.get(iDatesSize - 1);

        String dayRealmFile = Utils.getDayRealmFile(neIndexCode);
        List<HistoryDayQuote> indexDayList = null;

        RealmConfiguration realmConfig = new RealmConfiguration.Builder()
                .name(dayRealmFile)
                .deleteRealmIfMigrationNeeded()
                .build();
        Realm dayRealm = Realm.getInstance(realmConfig);
        RealmResults<HistoryDayQuote> results =
                dayRealm.where(HistoryDayQuote.class)
                        .between("date", startIDate, endIDate)
                        .sort("date", Sort.ASCENDING).findAll();
        if (results.size() > 0) {
            indexDayList = dayRealm.copyFromRealm(results);
        }
        dayRealm.close();
        if (null == indexDayList)
            return null;
        if (indexDayList.size() == iDatesSize)
            return Arrays.asList(indexDayList.toArray(new KLineChartQuote[0]));

        int lastIndexRecordIDate = indexDayList.get(indexDayList.size() - 1).getQuoteIDate();
        int lastRefIDate = iDateList.get(iDatesSize - 1);
        if (lastIndexRecordIDate < lastRefIDate &&
                lastRefIDate == Utils.getCurrentIDate()) {
            TodayQuote tq = getTodayQuoteByCode(neIndexCode);
            if ((tq != null) && (Utils.getIDateFromDate(tq.getUpdateDate()) == lastRefIDate)) {
                indexDayList.add(new HistoryDayQuote(lastRefIDate, tq));
            } else {
                indexDayList.add(new HistoryDayQuote());
            }
        }
        if (indexDayList.size() > iDatesSize) {
             for (int i = indexDayList.size() - 1; i >=0; i--) {
                HistoryDayQuote indexQuote = indexDayList.get(i);
                int iqDate = indexQuote.getQuoteIDate();
                if (!iDateList.contains(iqDate)) {
                    indexDayList.remove(indexQuote);
                }
            }
        }

        if (indexDayList.size() != iDateList.size()) {
            return null;
        }

        return Arrays.asList(indexDayList.toArray(new KLineChartQuote[0]));
    }

}
